//
//  PictureCellView.swift
//  微博
//
//  Created by mac on 15/12/20.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SDWebImage

//设置图片的间距
private let cellid = "pictureCell"
private let pictureCellMargin:CGFloat = 5
class PictureCellView: UICollectionView {
    
    //添加图片urls的属性
    var urls: [NSURL]?{
        didSet{
//            countLabel.text = "\(urls?.count ?? 0)"
           //根据返回多少图片设置约束
            let size = setContentSize()
            self.snp_updateConstraints{ (make) -> Void in
                make.size.equalTo(size)
            }
            //刷新列表
            self.reloadData()
        }
    }
    
    //构造方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //自定义flowLayout
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = pictureCellMargin
        flowLayout.minimumInteritemSpacing = pictureCellMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        //设置颜色
        backgroundColor = UIColor.whiteColor()
        //注册cell
        self.registerClass(pictureCell.self, forCellWithReuseIdentifier: cellid)
        //设置数据源代理
        self.dataSource = self
        self.delegate = self
        //设置ui
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置大小
    private func setContentSize() -> CGSize {
        //设置最大距离
        let sizeMax = screenWidth - 2 * StatusCellMarigin
        //设置item的size
        let itemSize = (sizeMax - 2 * pictureCellMargin) / 3
        
        //设置item的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemSize, height: itemSize)
        //获取urlcount
        let urlCount = urls?.count ?? 0
        if urlCount == 0 {
            return CGSizeZero
        }
        if urlCount == 1 {
            //TODO:根据图片大小设置图片
            var size = CGSize(width: 180, height: 120)
            //图片已经下载完成,此时从缓存中获取图片
            //获取单张图片的urlkey
            let key = urls?.last?.absoluteString
            //获取图片
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            if image != nil {
                size = image.size
            }
            //设置item的size
            layout.itemSize = size
            return size
        }
        if urlCount == 4 {
            let w = 2 * itemSize + pictureCellMargin
            return CGSize(width: w, height: w)
        }
        //当程序走到这的时候,就会到这个位置
        //判断有多少行
        let row = (CGFloat)((urlCount-1) / 3) + 1
        return CGSize(width: sizeMax, height: itemSize * row + pictureCellMargin * (row - 1))
    }
    //设置ui
    private func setupUI() {
        self.addSubview(countLabel)
        //添加约束
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    //懒加载视图
    //添加一个文本视图来着标示有多少张图片
    private lazy var countLabel:UILabel = UILabel(content: "", color: UIColor.blackColor(), fontSize: 20)

}
//添加cell
extension PictureCellView : UICollectionViewDataSource,UICollectionViewDelegate{
    //没有实现两个必选的数组源方法
//     func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//        return 1
//// }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellid, forIndexPath: indexPath) as! pictureCell
        cell.url = urls![indexPath.item]
        return cell
    }
    //选中的item
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //创建browser
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = urls?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        
        /*
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        
        browser.sourceImagesContainerView = 原图的父控件;
        
        browser.imageCount = 原图的数量;
        
        browser.currentImageIndex = 当前需要展示图片的index;
        
        browser.delegate = 代理;
        
        [browser show]; // 展示图片浏览器*/
    }
    
}


extension PictureCellView :SDPhotoBrowserDelegate {
    //返回图片
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        if let cell = self.cellForItemAtIndexPath(indexPath) as? pictureCell {
            return cell.picture.image
        }
        return nil
    }
    //返回高清的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        if let placeHolderstring = urls?[index].absoluteString {
            let highQualityImageStr = placeHolderstring.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
            return NSURL(string: highQualityImageStr)
        }
        return nil
    }
    
    /*
    UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index { ； }
    // 返回高质量图片的url
    
    (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    
    }
*/
}

class pictureCell :UICollectionViewCell {
    
    var url:NSURL? {
        didSet{
            //加载网络图片
            picture.sd_setImageWithURL(url)
        }
    }
    
    //重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.randomColor()
        //设置UI
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置ui
    private func setupUI() {
        addSubview(picture)
        //设置约束
        picture.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
    }
    //懒加载
    private lazy var picture:UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
}

